import { isExternal } from '@/utils'
import { RouteRecordRaw } from 'vue-router'
import { TagView } from '@/stores/interface'
type OnlyOneChildType = RouteRecordRaw & { noShowingChildren?: boolean }

interface HasOneShowingChild {
  oneShowingChild?: boolean
  onlyOneChild?: OnlyOneChildType
}
/**
 * 判断当前路由是否只有一个显示的子路由
 *
 * @param children 子路由数组
 * @param parent 父级路由对象
 * @returns 布尔值，表示是否只有一个显示的子路由
 */
export const hasOneShowingChild = (children: RouteRecordRaw[] = [], parent: RouteRecordRaw): HasOneShowingChild => {
  const onlyOneChild = ref<OnlyOneChildType>()

  // 筛选出需要显示的子路由
  const showingChildren = children.filter((route: RouteRecordRaw) => {
    const meta = route.meta ?? {}
    if (meta?.hidden) {
      return false
    } else {
      meta!.hidden = false
      // 如果只有一个显示子项
      onlyOneChild.value = route
      return true
    }
  })

  // 当只有一个子路由器时，默认显示子路由器
  if (showingChildren.length === 1) {
    return {
      oneShowingChild: true,
      onlyOneChild: unref(onlyOneChild)
    }
  }

  // 如果没有要显示的子路由器，则显示父路由器
  if (showingChildren.length === 0) {
    onlyOneChild.value = { ...parent, path: '', noShowingChildren: true }
    return {
      oneShowingChild: true,
      onlyOneChild: unref(onlyOneChild)
    }
  }
  return {
    oneShowingChild: false,
    onlyOneChild: unref(onlyOneChild)
  }
}

/**
 * 路由路径解析
 *
 * @param routePath 路由路径
 * @param routeQuery 路由路径参数
 * @returns 绝对路径
 */
export const pathResolve = (routePath: string, basePath: string) => {
  if (isExternal(routePath)) {
    return routePath
  }
  if (isExternal(basePath)) {
    return basePath
  }
  const childPath = routePath.startsWith('/') || !routePath ? routePath : `/${routePath}`
  return `${basePath}${childPath}`.replace(/\/\//g, '/').trim()
}

export const filterAffixTags = (routes: RouteRecordRaw[], basePath = '') => {
  let tags: TagView[] = []
  routes.forEach(route => {
    const meta = route.meta ?? {}
    const tagPath = pathResolve(route.path, basePath)
    if (meta?.affix) {
      tags.push({
        path: tagPath,
        fullPath: tagPath,
        name: String(route.name),
        title: route.meta?.title || 'no-name',
        affix: route.meta?.affix,
        keepAlive: route.meta?.keepAlive
      } as TagView)
    }
    if (route.children) {
      const tempTags: TagView[] = filterAffixTags(route.children, basePath + route.path)
      if (tempTags.length >= 1) {
        tags = [...tags, ...tempTags]
      }
    }
  })
  return tags
}
